import pandas as pd
import numpy as np
import random
from datetime import datetime, timedelta

# 设置随机种子，保证结果可复现
np.random.seed(42)
random.seed(42)

# 生成数据的数量
num_records = 500

# 定义可能的产品类别和地区
categories = ["电子", "服装", "食品", "家居", "图书"]
regions = ["华东", "华北", "华南", "西北", "西南", "东北"]

# 生成订单ID
order_ids = [f"ORD-{i + 1000}" for i in range(num_records)]

# 生成随机订单日期（过去1年内）
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
order_dates = []
for _ in range(num_records):
    # 生成两个日期之间的随机日期
    random_days = random.randint(0, 365)
    order_date = start_date + timedelta(days=random_days)
    order_dates.append(order_date.strftime("%Y-%m-%d"))

# 随机选择产品类别和地区
categories_data = [random.choice(categories) for _ in range(num_records)]
regions_data = [random.choice(regions) for _ in range(num_records)]

# 生成销售额（10-1000之间的随机数，约5%的缺失值）
sales_data = np.random.uniform(10, 1000, num_records)
# 设置约5%的缺失值
missing_indices = random.sample(range(num_records), int(0.05 * num_records))
for idx in missing_indices:
    sales_data[idx] = np.nan

# 生成利润（销售额的10%-30%之间，约8%的异常负值）
profit_data = []
for i in range(num_records):
    if not np.isnan(sales_data[i]):
        # 正常利润是销售额的10%-30%
        profit_rate = random.uniform(0.1, 0.3)
        profit = sales_data[i] * profit_rate

        # 约8%的概率设置为负值（异常值）
        if random.random() < 0.08:
            profit = -abs(profit)  # 确保是负值

        profit_data.append(profit)
    else:
        profit_data.append(np.nan)  # 销售额缺失时利润也缺失

# 创建DataFrame
df = pd.DataFrame({
    "order_id": order_ids,
    "order_date": order_dates,
    "category": categories_data,
    "sales": sales_data,
    "profit": profit_data,
    "region": regions_data
})

# 保存为CSV文件
df.to_csv("sales_data.csv", index=False, encoding="utf-8")

print(f"已生成sales_data.csv文件，包含{num_records}条记录")
